<template>
  <div style="padding: 2rem;">
    <el-form :inline="true" :model="searchForm" class="demo-form-inline">
      <el-form-item label="广告标题">
        <el-input v-model="searchForm.title" placeholder="请输入广告标题"></el-input>
      </el-form-item>
      <el-form-item label="广告种类">
        <el-select v-model="searchForm.categoryId" placeholder="请选择广告种类" clearable filterable>
          <el-option
            v-for="item in adCategories"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="广告链接">
        <el-input v-model="searchForm.url" placeholder="请输入广告链接"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSearch" plain>查询</el-button>
        <el-button type="success" @click="openDialog('add')" plain>新增广告</el-button>
        <el-button type="danger" @click="handleLogout" plain>退出登录</el-button>
      </el-form-item>
    </el-form>
    <el-table :data="tableData" style="width: 100%; margin-top: 15px;">
      <el-table-column prop="id" label="广告ID"></el-table-column>
      <el-table-column prop="title" label="广告标题"></el-table-column>
      <el-table-column prop="categoryName" label="广告种类"></el-table-column>
      <el-table-column prop="url" label="广告链接"></el-table-column>
      <el-table-column prop="pic" label="广告图片">
        <template #default="scope">
          <el-image :src="scope.row.pic" style="height: 100px"></el-image>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template #default="scope">
          <el-button link type="primary" @click="openDialog('edit', scope.row)">编辑</el-button>
          <el-button link type="danger" size="small" @click="handleDelete(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination-container" style="margin-top: 20px; width: 100%;display: flex;justify-content: center;">
      <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[5, 10, 20, 40]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
    </div>
    <el-dialog v-model="dialogVisible" :title="dialogTitle" align-center>
      <el-form :model="editForm" style="padding: 6px">
        <el-form-item label="广告标题" style="margin-bottom: 20px;">
          <el-input v-model="editForm.title"></el-input>
        </el-form-item>
        <el-form-item label="广告种类" style="margin-bottom: 20px;">
          <el-select v-model="editForm.categoryId">
            <el-option
              v-for="item in adCategories"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="广告链接" style="margin-bottom: 20px;">
          <el-input v-model="editForm.url"></el-input>
        </el-form-item>
        <el-form-item label="广告图片" style="margin-bottom: 20px;">
          <input type="file" @change="handleFileChange" />
          <el-input v-model="editForm.pic" readonly></el-input>
          <el-image v-if="previewImage" :src="previewImage" style="height: 150px; margin-top: 10px;"></el-image>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSave">保存</el-button>
          <el-button @click="dialogVisible = false">取消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { getAdCategoryList, searchAd, updateAd, deleteAd, addAd, getOssSignature } from "@/api/advertisement"
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'

const router = useRouter()

const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const tableData = ref([])
const adCategories = ref([])

const searchForm = ref({
  title: '',
  categoryId: null,
  url: ''
})

const dialogVisible = ref(false)
const dialogTitle = ref('')
const editForm = ref({
  id: null,
  title: '',
  categoryId: null,
  url: '',
  pic: ''
})

const selectedFile = ref(null)
const previewImage = ref('')

const fetchAdData = async () => {
  try {
    const response = await searchAd(currentPage.value, pageSize.value, searchForm.value)
    if (response.code === 200) {
      tableData.value = response.data.pageResult.rows
      total.value = response.data.pageResult.total
    } else {
      ElMessage.error(response.message)
    }
  } catch (error) {
    ElMessage.error('获取广告数据失败')
  }
}

const fetchAdCategories = async () => {
  try {
    const response = await getAdCategoryList()
    if (response.code === 200) {
      adCategories.value = response.data.list
    } else {
      ElMessage.error(response.message)
    }
  } catch (error) {
    ElMessage.error('获取广告种类失败')
  }
}

const handleSearch = () => {
  currentPage.value = 1
  fetchAdData()
}

const handleSizeChange = (val: number) => {
  pageSize.value = val
  fetchAdData()
}

const handleCurrentChange = (val: number) => {
  currentPage.value = val
  fetchAdData()
}

const openDialog = (type, row = null) => {
  if (type === 'add') {
    dialogTitle.value = '新增广告'
    editForm.value = {
      id: null,
      title: '',
      categoryId: null,
      url: '',
      pic: ''
    }
    previewImage.value = ''
  } else if (type === 'edit' && row) {
    dialogTitle.value = '编辑广告'
    editForm.value = { ...row }
    previewImage.value = row.pic
  }
  dialogVisible.value = true
}

const handleFileChange = (event) => {
  selectedFile.value = event.target.files[0]
  if (selectedFile.value) {
    previewImage.value = URL.createObjectURL(selectedFile.value)
  }
}

const uploadToOss = async (file) => {
  try {
    const response = await getOssSignature()

    const data = response
    const formData = new FormData()
    formData.append('x-oss-signature-version', data.version)
    formData.append('x-oss-credential', data.credential)
    formData.append('x-oss-date', data.ossdate)
    formData.append('x-oss-signature', data.signature)
    formData.append('success_action_status', '200')
    formData.append('policy', data.policy)
    formData.append('x-oss-security-token', data.token)
    formData.append('key', data.dir + file.name)
    formData.append('file', file)

    const uploadResponse = await fetch(data.host, {
      method: 'POST',
      body: formData
    })

    if (!uploadResponse.ok) {
      throw new Error('上传失败')
    }

    return `${data.host}/${data.dir}${file.name}`
  } catch (error) {
    ElMessage.error(error.message)
    throw error
  }
}

const handleSave = async () => {
  try {
    if (selectedFile.value) {
      const picUrl = await uploadToOss(selectedFile.value)
      editForm.value.pic = picUrl
    }

    let response
    if (editForm.value.id) {
      response = await updateAd(editForm.value)
    } else {
      response = await addAd(editForm.value)
    }

    if (response.code === 200) {
      ElMessage.success('保存成功')
      dialogVisible.value = false
      fetchAdData()
    } else {
      ElMessage.error(response.message)
    }
  } catch (error) {
    ElMessage.error('保存广告信息失败')
  }
}

const handleDelete = async (id) => {
  try {
    const response = await deleteAd(id)
    if (response.code === 200) {
      ElMessage.success('删除成功')
      fetchAdData()
    } else {
      ElMessage.error(response.message)
    }
  } catch (error) {
    ElMessage.error('删除广告信息失败')
  }
}

const handleLogout = () => {
  localStorage.removeItem('token')
  ElMessage.success('退出登录成功')
  router.push('/login')
}

onMounted(() => {
  fetchAdData()
  fetchAdCategories()
})
</script>

<style scoped>
.demo-form-inline .el-form-item {
  margin-right: 20px;
}
</style>
